package com.pdf.pdfserver.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.common.SolrDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Objects;

/**
 * @Author songfz
 * @Description solr 文档数据转换工具
 * @Date 2022/1/11
 */
public class SolrDocumentUtil {

    private static Logger LOG = LoggerFactory.getLogger(SolrDocumentUtil.class);

    /**
     * solrDocument转换对象
     *
     * @param solrDocument
     * @param tClass
     * @return
     */
    public static <T> T convert(SolrDocument solrDocument, Class<T> tClass) {

        if (Objects.isNull(solrDocument)) {
            return null;
        }

        try {
            T t = tClass.getDeclaredConstructor().newInstance();
            for (String solrFieldName : solrDocument.getFieldNames()) {


                for (Field field : tClass.getDeclaredFields()) {

                    org.apache.solr.client.solrj.beans.Field annotation = field.getAnnotation(org.apache.solr.client.solrj.beans.Field.class);

                    String fieldName = StringUtils.isNotBlank(annotation.value()) ? annotation.value() : field.getName();
                    if (fieldName.equals(solrFieldName)) {
                        Class<?> fieldType = toType(field.getType());
                        Method method = tClass.getMethod(dynamicMethodName(field.getName(), "set"), fieldType);

                        method.invoke(t, fieldType.cast(solrDocument.getFieldValue(solrFieldName)));
                    }
                }

            }
            return tClass.cast(t);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        return null;
    }

    private static Class<?> toType(Class<?> fieldType) {

        if (fieldType.equals(Integer.TYPE)) {
            fieldType = Integer.class;
        } else if (fieldType.equals(Float.TYPE)) {
            fieldType = Float.class;
        } else if (fieldType.equals(Double.TYPE)) {
            fieldType = Double.class;
        } else if (fieldType.equals(Boolean.TYPE)) {
            fieldType = Boolean.class;
        } else if (fieldType.equals(Short.TYPE)) {
            fieldType = Short.class;
        } else if (fieldType.equals(Long.TYPE)) {
            fieldType = Long.class;
        } else if (fieldType.equals(String.class)) {
            fieldType = String.class;
        } else if (fieldType.equals(Collection.class)) {
            fieldType = Collection.class;
        }
        return fieldType;
    }

    private static String dynamicMethodName(String name, String setOrGet) {
        String setMethodName = setOrGet
                + name.substring(0, 1).toUpperCase()
                + name.substring(1);
        return setMethodName;
    }
}
